package filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * 登录过滤器，当用户进行管理操作时判断是否登录
 */
@WebFilter(urlPatterns = "/sys/*")
public class LoginFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        //强制转换为HttpServletRequest
        HttpServletRequest request = (HttpServletRequest) req;
        //1.获取资源的请求路径(谁请求这个资源)
        String uri = request.getRequestURI();
        //2.判断是否包含与登录相关的资源路径，并排除css/jd/图片/验证码等资源
        if(uri.contains("login")){
            //如果包含，说明用户就是想去登录，直接放行
            chain.doFilter(req, resp);
        }else{
            //如果不包含，说明用户并不是在执行登录操作，需要判断用户是否已经登录
            //3.从Session中获取User对象
            Object user = request.getSession().getAttribute("userOnLogin");
            if (user != null){
                //用户已登录，放行
                chain.doFilter(req,resp);
            }else {
                //用户未登录，跳转回主页
                request.setAttribute("error","请先登录");
                request.getRequestDispatcher("/index").forward(req,resp);
            }
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }
}
